# -*- coding: utf-8 -*-
import time
import machine
import dht
from machine import ADC, PWM, Pin, Timer
from machine import Pin  #载入Pin模块
io = Pin(2, Pin.OUT)    # 在GPIO0上创建输出
io.on()
try:
    import ujson as json
except ImportError:
    import json

class Func():

    def send(self, text=''):
        self.mqtt_send(text)
    def mqtt_send(self, Data=''):
        pass




    def dhtData(self):
        try:
            d = dht.DHT11(machine.Pin(5))
            d.measure()
            return str(d.temperature()) , str(d.humidity())   
        except Exception as b: 
            print(b)
            return "None","None"  

    # 回调处理
    def mqtt_receive(self, topic, rejson):
        print("回调收到消息", rejson )

        if 'type' in dict(rejson).keys():
            
            if rejson['type'] == 'dht':
                io.off()
                temp_val,humi_val =self.dhtData()
                if temp_val == "None":
                    time.sleep(1)
                    temp_val,humi_val =self.dhtData()
                self.send(  {'type':'dht','message': {'temperature': str(temp_val), 'humidity': str(humi_val)}   })
                io.on()
             


            if rejson['type'] == 'dhtWx':
                io.off()
                temp_val,humi_val =self.dhtData()
                if temp_val == "None":
                    time.sleep(1)
                    temp_val,humi_val =self.dhtData()
                self.send(  {'type':'dhtWx','message': {'temperature': str(temp_val), 'humidity': str(humi_val)}   })
                io.on()
        